import { defineStore } from 'pinia'

export interface UserState {
  name: string
  token: string
  role: string
  phone: string
}

interface SetUserPayload {
  name?: string
  token?: string
  role?: string
  phone?: string
}

export const useUserStore = defineStore<'user', UserState, {}, {
  setUser(payload: SetUserPayload): void
  setRole(role: string): void
  logout(): void
}>(
  'user',
  {
    state: (): UserState => ({
      name: '',
      token: '',
      role: '',
      phone: ''
    }),
    actions: {
      setUser({ name, token, role, phone }: SetUserPayload) {
        if (typeof name === 'string') this.name = name
        if (typeof token === 'string') this.token = token
        if (typeof role === 'string') this.role = role
        if (typeof phone === 'string') this.phone = phone
      },
      setRole(role: string) {
        this.role = role
      },
      logout() {
        this.name = ''
        this.token = ''
        this.role = ''
        this.phone = ''
      }
    },
    persist: true
  }
) 
